<!--
  智慧社区管理系统 - 安保路线管理页面
  严格按照《App端编码规范权威标准声明.md》Vue组件规范实现
  
  @author Wu.Liang
  @date 2025-01-30
  @description 安保巡逻路线管理，支持基于数据权限的社区过滤
-->
<template>
  <div class="security-route-management">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <div class="header-title">
          <el-icon size="24" class="title-icon"><MapLocation /></el-icon>
          <h2>路线管理</h2>
        </div>
        <div class="header-actions">
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>
            新增路线
          </el-button>
          <el-button @click="handleRefresh">
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
        </div>
      </div>
    </div>

    <!-- 搜索表单 -->
    <div class="search-form">
      <el-form :model="searchForm" :inline="true" class="search-form-inline">
        <el-form-item label="所属社区">
          <el-input
            v-model="searchForm.communityName"
            placeholder="请输入社区名称"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-select
            v-model="searchForm.status"
            placeholder="请选择状态"
            clearable
            style="width: 150px"
          >
            <el-option label="启用" :value="1" />
            <el-option label="停用" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="路线类型">
          <el-select
            v-model="searchForm.routeType"
            placeholder="请选择路线类型"
            clearable
            style="width: 150px"
          >
            <el-option label="巡逻路线" value="patrol" />
            <el-option label="检查点" value="checkpoint" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><RefreshLeft /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 数据表格 -->
    <div class="table-container">
      <el-table
        v-loading="loading"
        :data="tableData"
        stripe
        border
        style="width: 100%"
        empty-text="暂无路线数据"
      >
        <el-table-column prop="routeName" label="路线名称" min-width="150" />
        <el-table-column prop="routeTypeDesc" label="路线类型" width="120" />
        <el-table-column prop="communityName" label="所属社区" min-width="150" />
        <el-table-column prop="frequencyDesc" label="巡逻频次" width="120" />
        <el-table-column prop="durationMinutes" label="预计时长(分钟)" width="130" />
        <el-table-column prop="statusDesc" label="状态" width="80">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'danger'">
              {{ row.statusDesc }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="160">
          <template #default="{ row }">
            {{ formatDateTime(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button
              type="primary"
              size="small"
              @click="handleView(row)"
            >
              查看
            </el-button>
            <el-button
              type="warning"
              size="small"
              @click="handleEdit(row)"
            >
              编辑
            </el-button>
            <el-button
              :type="row.status === 1 ? 'danger' : 'success'"
              size="small"
              @click="handleToggleStatus(row)"
            >
              {{ row.status === 1 ? '停用' : '启用' }}
            </el-button>
            <el-button
              type="danger"
              size="small"
              @click="handleDelete(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页组件 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="pagination.current"
        v-model:page-size="pagination.size"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="800px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="120px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="路线名称" prop="routeName">
              <el-input v-model="formData.routeName" placeholder="请输入路线名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="路线类型" prop="routeType">
              <el-select v-model="formData.routeType" placeholder="请选择路线类型" style="width: 100%">
                <el-option label="巡逻路线" value="patrol" />
                <el-option label="检查点" value="checkpoint" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="所属社区" prop="communityId">
              <el-select v-model="formData.communityId" placeholder="请选择社区" style="width: 100%">
                <el-option
                  v-for="community in communityList"
                  :key="community.id"
                  :label="community.name"
                  :value="community.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="巡逻频次" prop="frequency">
              <el-select v-model="formData.frequency" placeholder="请选择巡逻频次" style="width: 100%">
                <el-option label="每小时" value="hourly" />
                <el-option label="每2小时" value="every_2_hours" />
                <el-option label="每日" value="daily" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="预计时长(分钟)" prop="durationMinutes">
              <el-input-number
                v-model="formData.durationMinutes"
                :min="1"
                :max="1440"
                placeholder="请输入预计时长"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-select v-model="formData.status" placeholder="请选择状态" style="width: 100%">
                <el-option label="启用" :value="1" />
                <el-option label="停用" :value="2" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="路线描述" prop="description">
          <el-input
            v-model="formData.description"
            type="textarea"
            :rows="3"
            placeholder="请输入路线描述"
          />
        </el-form-item>
        <el-form-item label="检查点信息" prop="checkpoints">
          <el-input
            v-model="formData.checkpoints"
            type="textarea"
            :rows="4"
            placeholder="请输入检查点信息（JSON格式）"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitting">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 查看详情对话框 -->
    <el-dialog
      v-model="viewDialogVisible"
      title="路线详情"
      width="600px"
      :close-on-click-modal="false"
    >
      <div v-if="viewData" class="route-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="路线名称">
            {{ viewData.routeName }}
          </el-descriptions-item>
          <el-descriptions-item label="路线类型">
            {{ viewData.routeTypeDesc }}
          </el-descriptions-item>
          <el-descriptions-item label="所属社区">
            {{ viewData.communityName }}
          </el-descriptions-item>
          <el-descriptions-item label="巡逻频次">
            {{ viewData.frequencyDesc }}
          </el-descriptions-item>
          <el-descriptions-item label="预计时长">
            {{ viewData.durationMinutes }} 分钟
          </el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="viewData.status === 1 ? 'success' : 'danger'">
              {{ viewData.statusDesc }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">
            {{ formatDateTime(viewData.createTime) }}
          </el-descriptions-item>
          <el-descriptions-item label="创建人">
            {{ viewData.createByName }}
          </el-descriptions-item>
          <el-descriptions-item label="路线描述" :span="2">
            {{ viewData.description || '无' }}
          </el-descriptions-item>
          <el-descriptions-item label="检查点信息" :span="2">
            <pre class="checkpoints-info">{{ viewData.checkpoints || '无' }}</pre>
          </el-descriptions-item>
        </el-descriptions>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { MapLocation, Plus, Refresh, Search, RefreshLeft } from '@element-plus/icons-vue'
import { getSecurityRoutePage, createSecurityRoute, updateSecurityRoute, deleteSecurityRoute, updateSecurityRouteStatus } from '@/api/work/security'
import type { SecurityRouteInfo, SecurityRouteQueryParams } from '@/api/work/security'

// ========================= 响应式数据 =========================

// 加载状态
const loading = ref(false)

// 搜索表单
const searchForm = reactive<SecurityRouteQueryParams>({
  routeName: '',
  status: undefined,
  routeType: ''
})

// 表格数据
const tableData = ref<SecurityRouteInfo[]>([])

// 分页数据
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 对话框状态
const dialogVisible = ref(false)
const viewDialogVisible = ref(false)
const submitting = ref(false)

// 表单数据
const formData = ref<Partial<SecurityRouteInfo>>({})
const formRef = ref<FormInstance>()

// 查看数据
const viewData = ref<SecurityRouteInfo | null>(null)

// 社区列表
const communityList = ref([
  { id: 1, name: '示例社区1' },
  { id: 2, name: '示例社区2' }
])

// ========================= 计算属性 =========================

const dialogTitle = computed(() => {
  return formData.value.id ? '编辑路线' : '新增路线'
})

// ========================= 表单验证规则 =========================

const formRules: FormRules = {
  routeName: [
    { required: true, message: '请输入路线名称', trigger: 'blur' }
  ],
  routeType: [
    { required: true, message: '请选择路线类型', trigger: 'change' }
  ],
  communityId: [
    { required: true, message: '请选择所属社区', trigger: 'change' }
  ],
  frequency: [
    { required: true, message: '请选择巡逻频次', trigger: 'change' }
  ],
  durationMinutes: [
    { required: true, message: '请输入预计时长', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
}

// ========================= 方法定义 =========================

/**
 * 格式化日期时间
 */
const formatDateTime = (dateTime: string) => {
  if (!dateTime) return ''
  return new Date(dateTime).toLocaleString('zh-CN')
}

/**
 * 获取路线列表数据
 */
const fetchData = async () => {
  try {
    loading.value = true
    const params: SecurityRouteQueryParams = {
      pageNum: pagination.current,
      pageSize: pagination.size,
      ...searchForm
    }
    
    const response = await getSecurityRoutePage(params)
    tableData.value = response.records || []
    pagination.total = response.total || 0
  } catch (error) {
    console.error('获取路线列表失败:', error)
    ElMessage.error('获取路线列表失败')
  } finally {
    loading.value = false
  }
}

/**
 * 搜索处理
 */
const handleSearch = () => {
  pagination.current = 1
  fetchData()
}

/**
 * 重置搜索
 */
const handleReset = () => {
  Object.assign(searchForm, {
    routeName: '',
    status: undefined,
    routeType: ''
  })
  handleSearch()
}

/**
 * 刷新数据
 */
const handleRefresh = () => {
  fetchData()
}

/**
 * 分页大小改变
 */
const handleSizeChange = (size: number) => {
  pagination.size = size
  pagination.current = 1
  fetchData()
}

/**
 * 当前页改变
 */
const handleCurrentChange = (current: number) => {
  pagination.current = current
  fetchData()
}

/**
 * 新增路线
 */
const handleAdd = () => {
  formData.value = {
    routeName: '',
    routeType: '',
    communityId: undefined,
    frequency: '',
    durationMinutes: undefined,
    status: 1,
    description: '',
    checkpoints: ''
  }
  dialogVisible.value = true
}

/**
 * 编辑路线
 */
const handleEdit = (row: SecurityRouteInfo) => {
  formData.value = { ...row }
  dialogVisible.value = true
}

/**
 * 查看路线详情
 */
const handleView = (row: SecurityRouteInfo) => {
  viewData.value = row
  viewDialogVisible.value = true
}

/**
 * 切换路线状态
 */
const handleToggleStatus = async (row: SecurityRouteInfo) => {
  try {
    const newStatus = row.status === 1 ? 2 : 1
    const action = newStatus === 1 ? '启用' : '停用'
    
    await ElMessageBox.confirm(
      `确定要${action}路线"${row.routeName}"吗？`,
      '确认操作',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await updateSecurityRouteStatus(row.id, newStatus)
    ElMessage.success(`${action}成功`)
    fetchData()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('切换状态失败:', error)
      ElMessage.error('操作失败')
    }
  }
}

/**
 * 删除路线
 */
const handleDelete = async (row: SecurityRouteInfo) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除路线"${row.routeName}"吗？删除后不可恢复！`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await deleteSecurityRoute(row.id)
    ElMessage.success('删除成功')
    fetchData()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

/**
 * 提交表单
 */
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    submitting.value = true
    
    if (formData.value.id) {
      // 编辑
      await updateSecurityRoute(formData.value.id, formData.value)
      ElMessage.success('更新成功')
    } else {
      // 新增
      await createSecurityRoute(formData.value)
      ElMessage.success('创建成功')
    }
    
    dialogVisible.value = false
    fetchData()
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error('操作失败')
  } finally {
    submitting.value = false
  }
}

// ========================= 生命周期 =========================

onMounted(() => {
  fetchData()
})
</script>

<style scoped lang="scss">
.security-route-management {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;

  .page-header {
    background: white;
    padding: 20px;
    border-radius: 8px;
    margin-bottom: 20px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);

    .header-content {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .header-title {
        display: flex;
        align-items: center;
        gap: 12px;

        .title-icon {
          color: #409eff;
        }

        h2 {
          margin: 0;
          color: #303133;
          font-size: 20px;
          font-weight: 600;
        }
      }

      .header-actions {
        display: flex;
        gap: 12px;
      }
    }
  }

  .search-form {
    background: white;
    padding: 20px;
    border-radius: 8px;
    margin-bottom: 20px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);

    .search-form-inline {
      .el-form-item {
        margin-bottom: 0;
      }
    }
  }

  .table-container {
    background: white;
    padding: 20px;
    border-radius: 8px;
    margin-bottom: 20px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  }

  .pagination-container {
    display: flex;
    justify-content: center;
    background: white;
    padding: 20px;
    border-radius: 8px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  }

  .route-detail {
    .checkpoints-info {
      background-color: #f5f5f5;
      padding: 10px;
      border-radius: 4px;
      font-family: 'Courier New', monospace;
      font-size: 12px;
      white-space: pre-wrap;
      word-break: break-all;
    }
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style>
